package com.sx.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author AdinZ
 * @date 2020/4/30 6:33 下午
 */
public class XmlUtils {

    private Document document;

    public XmlUtils(String xml) throws DocumentException {
        this.document = DocumentHelper.parseText(xml);
    }
    private Map<String,Object> reload(List<Element> list){
        Map<String,Object> map=new HashMap<>();
        for(Element el:list){
            if(el.elements().size()>0){
                map.put(el.getName(),this.reload(el.elements()));
            }else map.put(el.getName(),el.getText());
        }
        return map;
    }
    public Map<String,Object> toMap(){
        Map<String,Object> map=new HashMap<>();
        Element el=this.document.getRootElement();
        if(el.elements().size()>0){
            map.put(el.getName(),this.reload(el.elements()));
        }else map.put(el.getName(),el.getText());

        return map;
    }
    public JSONObject toJSON(){
        JSONObject map=new JSONObject();
        Element el=this.document.getRootElement();
        if(el.elements().size()>0){
            map.put(el.getName(),this.reload(el.elements()));
        }else map.put(el.getName(),el.getText());
        return map;
    }

}
